package
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	
	import mx.core.UIComponent;
	
	public class DisplayListRenderer extends UIComponent
	{
		[Bindable]
		public var numDisplayObjects:uint = 1000;
		
		public function DisplayListRenderer()
		{
			super();
			
			addEventListener(Event.ADDED_TO_STAGE, addedToStage);
		}
		
		private function addedToStage(event:Event):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, addedToStage);
			addDisplayObjects();
			addEventListener(Event.ENTER_FRAME, update);
			addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
		}
		
		private function removedFromStage(event:Event):void
		{
			addEventListener(Event.ADDED_TO_STAGE, addedToStage);
			removeEventListener(Event.ENTER_FRAME, update);
		}
		
		private function update(event:Event):void 
		{
			for (var i:int = 0; i < numChildren; i++)
			{
				const comp:UIComponent = UIComponent(getChildAt(i));
				randomize(comp);
			}
		}
		
		private function addDisplayObjects():void 
		{
			for (var i:int = numChildren - 1; i > 0; i--)
			{
				removeChildAt(i);
			}
			
			for (i = 0; i < numDisplayObjects; i++) 
			{
				const comp:UIComponent = new UIComponent();
				randomize(comp);
				addChild(comp);
			}
		}
		
		private function randomize(comp:UIComponent):void 
		{
			comp.width = randomNum(10, 50);
			comp.height = randomNum(10, 50);
			comp.x = randomNum(0, stage.width - comp.width);
			comp.y = randomNum(0, stage.height - comp.height);
			comp.graphics.beginFill(randomColor());
			comp.graphics.drawRect(0, 0, comp.width, comp.height);
			comp.graphics.endFill();
		}
		
		private function randomColor():uint
		{
			return uint(Math.floor(Math.random() * 4294967295));
		}

		private function randomNum(min:uint, max:uint):uint 
		{
			return Math.round(Math.random() * (max - min)) + min;
		}
	}
}